import React, {useState} from "react";
import {
    Accordion,
    AccordionDetails,
    AccordionSummary,
    Button,
    Grid,
    InputAdornment,
    InputLabel,
    makeStyles,
    Paper,
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableRow,
    TextField,
    Typography
} from "@material-ui/core";
import DateFnsUtils from "@date-io/date-fns";
import {
    KeyboardDatePicker,
    KeyboardDateTimePicker,
    KeyboardTimePicker,
    MuiPickersUtilsProvider
} from "@material-ui/pickers";
import ExpandMoreIcon from "@material-ui/icons/ExpandMore";

import {getFullName} from "../../../shared/utilities/common.util";
import {getProducts, getRoutes, getTeamMembers, getVehicles} from "../../../shared/services/data.service";
import {AsyncSelect, Toolbar} from "../../../shared/components";

const useStyle = makeStyles(theme => ({
    paper: {padding: theme.spacing(3, 2)},
    accordionTitle: {backgroundColor: theme.palette.grey[200]}
}));

const AddPlan = ({onClose, onConfirm}) => {
    const classes = useStyle();
    const [state, setState] = useState({
        tslOrder: Date.now(),
        planDate: new Date(),
        driver: null,
        truck: null,
        route: null,
        product: null,
        loadStartTime: new Date(),
        fuel: '',
        eta: new Date()
    });

    const getDrivers = () => (
        new Promise((resolve, reject) => {
            getTeamMembers(200).then(res => resolve(res.data)).catch(error => reject(error));
        })
    );

    const getTrucks = () => (
        new Promise((resolve, reject) => {
            getVehicles(200).then(res => resolve(res.data)).catch(error => reject(error));
        })
    );

    const getRouteList = () => (
        new Promise((resolve, reject) => {
            getRoutes(200).then(res => resolve(res.data)).catch(error => reject(error));
        })
    );

    const getProductList = () => (
        new Promise((resolve, reject) => {
            getProducts(200).then(res => resolve(res.data)).catch(error => reject(error));
        })
    );

    const getProductRate = () => {
        let rate = '';
        if(state.route && state.product) {
            if(state.product.product_routes) {
                let productRoute = state.product.product_routes.find(item => item.route_id === state.route.id);
                if(productRoute) {
                    rate = productRoute.route_rate.rate_per_tone;
                }
            }
        }
        return rate;
    }


    const handleChange = (field, value) => {
        setState({...state, [field]: value});
    };

    return (
        <React.Fragment>
            <Grid container spacing={4}>
                <Toolbar
                    title="Add Plan"
                    actions={
                        <React.Fragment>
                            <Button color="primary" variant="contained" onClick={onConfirm}>Add</Button>
                            <Button variant="contained" onClick={onClose}>Cancel</Button>
                        </React.Fragment>
                    }
                />

                <Grid item xs={12}>
                    <Paper elevation={2} className={classes.paper}>
                        <Grid container spacing={3} alignItems={"center"}>
                            <Grid item xs={2}><InputLabel htmlFor="tslOrder">TSL Order No.</InputLabel></Grid>
                            <Grid item xs={4}>
                                <TextField
                                    id="tslOrder"
                                    variant="outlined"
                                    fullWidth disabled
                                    value={state.tslOrder}
                                />
                            </Grid>

                            <Grid item xs={2}><InputLabel htmlFor="planDate">Date</InputLabel></Grid>
                            <Grid item xs={4}>
                                <MuiPickersUtilsProvider utils={DateFnsUtils}>
                                    <KeyboardDatePicker
                                        id="planDate" autoOk
                                        variant="inline"
                                        inputVariant="outlined"
                                        format="dd-MMM-yyyy"
                                        value={state.planDate}
                                        onChange={date => handleChange('planDate', date)}
                                    />
                                </MuiPickersUtilsProvider>
                            </Grid>

                            <Grid item xs={2}><InputLabel htmlFor="driver">Driver</InputLabel></Grid>
                            <Grid item xs={4}>
                                <AsyncSelect
                                    id={"driver"}
                                    getOptionLabel={option => getFullName(option.first_name, option.last_name)}
                                    loadingMethod={getDrivers}
                                    onChange={(e, newValue) => handleChange('driver', newValue)}
                                />
                            </Grid>

                            <Grid item xs={2}><InputLabel htmlFor="truck">Truck</InputLabel></Grid>
                            <Grid item xs={4}>
                                <AsyncSelect
                                    id={"truck"}
                                    getOptionLabel={option => option.vehicle_number}
                                    loadingMethod={getTrucks}
                                    onChange={(e, newValue) => handleChange('truck', newValue)}
                                />
                            </Grid>

                            <Grid item xs={2}><InputLabel htmlFor="route">Route</InputLabel></Grid>
                            <Grid item xs={4}>
                                <AsyncSelect
                                    id={"route"}
                                    getOptionLabel={option => option.name}
                                    loadingMethod={getRouteList}
                                    onChange={(e, newValue) => handleChange('route', newValue)}
                                />
                            </Grid>

                            <Grid item xs={2}><InputLabel htmlFor="product">Product</InputLabel></Grid>
                            <Grid item xs={4}>
                                <AsyncSelect
                                    id={"product"}
                                    getOptionLabel={option => option.name}
                                    loadingMethod={getProductList}
                                    onChange={(e, newValue) => handleChange('product', newValue)}
                                />
                            </Grid>

                            <Grid item xs={2}><InputLabel htmlFor="source">Source</InputLabel></Grid>
                            <Grid item xs={4}>
                                <TextField
                                    name="source"
                                    fullWidth
                                    variant="outlined" disabled
                                    value={state.route?.source_address?.address1}
                                />
                            </Grid>

                            <Grid item xs={2}><InputLabel htmlFor="plannedTonnage">Planned Tonnage</InputLabel></Grid>
                            <Grid item xs={4}>
                                <TextField
                                    name="plannedTonnage"
                                    fullWidth
                                    variant="outlined" disabled
                                    value={state.product?.std_tonnage}
                                />
                            </Grid>

                            <Grid item xs={2}><InputLabel htmlFor="destination">Destination</InputLabel></Grid>
                            <Grid item xs={4}>
                                <TextField
                                    name="destination"
                                    fullWidth
                                    variant="outlined" disabled
                                    value={state.route?.destination_address?.address1}
                                />
                            </Grid>

                            <Grid item xs={2}><InputLabel htmlFor="productRate">Rate</InputLabel></Grid>
                            <Grid item xs={4}>
                                <TextField
                                    name="productRate"
                                    fullWidth
                                    variant="outlined" disabled
                                    value={getProductRate()}
                                />
                            </Grid>

                            <Grid item xs={2}><InputLabel htmlFor="loadStartTime">Planned Load Start Time</InputLabel></Grid>
                            <Grid item xs={4}>
                                <MuiPickersUtilsProvider utils={DateFnsUtils}>
                                    <KeyboardDateTimePicker
                                        id="loadStartTime"
                                        autoOk
                                        variant="inline"
                                        inputVariant="outlined"
                                        format="dd-MMM-yyyy hh:mm a"
                                        value={state.loadStartTime}
                                        onChange={dateTime => handleChange('loadStartTime', dateTime)}
                                    />
                                </MuiPickersUtilsProvider>
                            </Grid>

                            <Grid item xs={2}><InputLabel htmlFor="eta">Planned ETA at Destination</InputLabel></Grid>
                            <Grid item xs={4}>
                                <MuiPickersUtilsProvider utils={DateFnsUtils}>
                                    <KeyboardTimePicker
                                        id="eta"
                                        autoOk
                                        variant="inline"
                                        inputVariant="outlined"
                                        format="hh:mm a"
                                        value={state.eta}
                                        onChange={time => handleChange('eta', time)}
                                    />
                                </MuiPickersUtilsProvider>
                            </Grid>

                            <Grid item xs={2}><InputLabel htmlFor="std_distance_cycle">Planned
                                Distance</InputLabel></Grid>
                            <Grid item xs={4}>
                                <TextField
                                    id="std_distance_cycle"
                                    variant="outlined"
                                    fullWidth
                                    disabled
                                    InputProps={{endAdornment: <InputAdornment position="start">KM</InputAdornment>}}
                                    value={state.route?.std_distance_cycle}
                                />
                            </Grid>

                            <Grid item xs={2}><InputLabel htmlFor="std_cycle_hours">Planned Cycle
                                Time</InputLabel></Grid>
                            <Grid item xs={4}>
                                <TextField
                                    id="std_cycle_hours"
                                    variant="outlined"
                                    fullWidth
                                    disabled
                                    InputProps={{endAdornment: <InputAdornment position="start">hr(s)</InputAdornment>}}
                                    value={state.route?.std_cycle_hours}
                                />
                            </Grid>

                            <Grid item xs={2}><InputLabel htmlFor="fuel">Planned Fuel (to be filled)</InputLabel></Grid>
                            <Grid item xs={4}>
                                <TextField
                                    id="fuel"
                                    variant="outlined"
                                    fullWidth
                                    InputProps={{endAdornment: <InputAdornment position="start">ltr</InputAdornment>}}
                                    value={state.fuel}
                                    onChange={e => handleChange('fuel', e.target.value)}
                                />
                            </Grid>

                            <Grid item xs={12}>
                                <Accordion defaultExpanded elevation={0}>
                                    <AccordionSummary
                                        id="planned-stoppages-header"
                                        expandIcon={<ExpandMoreIcon/>}
                                        className={classes.accordionTitle}
                                    >
                                        <Typography variant={"h6"}>Planned Stoppages</Typography>
                                    </AccordionSummary>
                                    <AccordionDetails>
                                        <Table size="small">
                                            <TableHead>
                                                <TableRow>
                                                    <TableCell align={"justify"}>Distance</TableCell>
                                                    <TableCell align={"justify"}>Estimated Arrival Time</TableCell>
                                                    <TableCell align={"justify"}>Date & Time</TableCell>
                                                </TableRow>
                                            </TableHead>
                                            {state.route && <TableBody>
                                                {state.route.route_planner.route_stops.map(stop => (
                                                    <TableRow key={stop.id}>
                                                        <TableCell align={"justify"}>{stop.distance}</TableCell>
                                                        <TableCell align={"justify"}>
                                                            {stop.estimated_arrival_time}
                                                        </TableCell>
                                                        <TableCell align={"justify"}>
                                                            <MuiPickersUtilsProvider utils={DateFnsUtils}>
                                                                <KeyboardDateTimePicker
                                                                    autoOk variant="inline"
                                                                    format="dd-MMM-yyyy hh:mm a"
                                                                />
                                                            </MuiPickersUtilsProvider>
                                                        </TableCell>
                                                    </TableRow>
                                                ))}
                                            </TableBody>}
                                        </Table>
                                    </AccordionDetails>
                                </Accordion>
                            </Grid>
                        </Grid>
                    </Paper>
                </Grid>
            </Grid>
        </React.Fragment>
    );
};

export default AddPlan;
